#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <error.h>

using namespace std;
#define BUFFERSIZE 20

int main()
{
    int money = 10000;
    char buffer[20];
    int fd = open("./text1.txt", O_CREAT | O_WRONLY | O_TRUNC);
    if (fd < 0) 
    {
        perror("open error:");
        exit(-1);
    }

    /* 创建子进程 */
    pid_t pid = fork();

    if(pid < 0)
    {
        perror("fork error:");
        exit(-1);
    }
    else if(pid == 0)
    {   // 子进程
        sleep(3);
        cout << "child process" << endl;

        fd = open("./text1.txt", O_RDONLY);
        if (fd < 0) 
        {
            perror("open error:");
            exit(-1);
        }
        int assert = 0;
        read(fd, &assert, sizeof(assert));
        cout << "child assert = " << assert << endl;
    }
    else //(pid > 0)
    {   //父进程返回的是子进程id
        cout << "parent process" << endl;

        fd = open("./text1.txt", O_WRONLY);
        money += 5000000;
        
        write(fd, &money, sizeof(money));
        if (fd < 0) 
        {
            perror("open error:");
            exit(-1);
        }
        money -= 5000000;
        cout << "parent money = " << money << endl;
        close(fd);
    }
    



    
}
